package com.gh.rabbitmq.eight;

import com.gh.rabbitmq.utils.RabbitmqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Eric
 * @Date 2021/7/18 17:51
 * @Version 1.0
 * 死信队列
 */
public class Consumer01 {

    //普通交换机名称
    public static final String NORMAL_EXCHANGE="normal_exchange";
    //死信交换机名称
    public static final String DEAD_EXCHANGE="dead_exchange";
    //普通队列名称
    public static final String NORMAL_QUEUE="normal_queue";
    //死信队列名称
    public static final String DEAD_QUEUE="dead_queue";

    public static void main(String[] args) throws Exception{
        Channel channel = RabbitmqUtils.getChannel();
        //声明交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        //声明队列
        Map<String,Object> map=new HashMap<>();
        //过期时间
        //map.put("x-message-ttl",10000);
        //设置正常队列为死信队列
        map.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //设置死信routingKey
        map.put("x-dead-letter-routing-key","lisi");
        map.put("x-max-length",6);
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,map);

        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);
        //绑定普通交换机与队列
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        //绑定死信交换机与队列
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");
        System.out.println("等待接收消息....");
        //声明接收消息
        DeliverCallback deliverCallback=(consumerTag, message)->{
            System.out.println(new String(message.getBody()));
        };
        //取消消息时的回调
        CancelCallback cancelCallback= consumerTag->{
            System.out.println("消费消息被中断了");
        };

        channel.basicConsume(NORMAL_QUEUE,true,deliverCallback,cancelCallback);
    }

}
